package robot

import (
	"errors"
	"fmt"
	"gitee.com/zjlsliupei/gdingtalk"
	"gitee.com/zjlsliupei/ghelp"
	"net/url"
	"time"
)

type ThirdRobot struct {
	webHookUrl string
	secret     string
}

// NewThirdRobot 初始化自定义机器人
func NewThirdRobot(webHookUrl, secret string) (ThirdRobot, error) {
	t := ThirdRobot{
		webHookUrl: webHookUrl,
		secret:     secret,
	}
	return t, nil
}

// Send 向群机器人发送消息
// Send(map[string]interface{}{
////     "name": "sven",
////     "age": 18
//// })
func (third *ThirdRobot) Send(msgContent map[string]interface{}) error {
	_url, err := url.Parse(third.webHookUrl)
	if err != nil {
		return err
	}
	timestamp := time.Now().Unix() * 1000
	req := gdingtalk.NewRequest()
	res := req.SetMethod("post").
		SetBodyParam(msgContent).
		SetPath(_url.Path).
		AddQueryParam("timestamp", ghelp.ToString(timestamp)).
		AddQueryParam("sign", third.sign(timestamp)).
		AddQueryParam("access_token", _url.Query().Get("access_token")).
		Do()
	if res.IsSuccess() {
		return nil
	} else {
		return errors.New(res.GetErrmsg())
	}
}

func (third *ThirdRobot) sign(timestamp int64) string {
	str := fmt.Sprintf("%d\n%s", timestamp, third.secret)
	sign := ghelp.HmacSha256(str, third.secret)
	return sign
}
